legend_labels <- c(
  "East Asia & Pacific (excluding high income)" = "East Asia and Pacific",
  "ECA (excluding Russia)" = "Europe and Central Asia",
  "Latin America & Caribbean (excluding high income)" = "Latin America and the Caribbean", 
  "Middle East & North Africa (excluding high income)" = "Middle East and North Africa", 
  "South Asia (excluding high income)" = "South Asia", 
  "Sub-Saharan Africa (excluding high income)" = "Sub-Saharan Africa",
  "LMIC" = "Low- and middle-income economies"
)


# FORMAL SAVINGS 2024 LMIC + REGIONS

library(scales)
library(dplyr)
library(tidyr)
library(ggplot2)

# Define countries to include
c_list_agg <- c(
  "East Asia & Pacific (excluding high income)", "ECA (excluding Russia)", 
  "Latin America & Caribbean (excluding high income)", "Middle East & North Africa (excluding high income)", 
  "South Asia (excluding high income)", "Sub-Saharan Africa (excluding high income)", "LMIC"
)

# Prepare the data
plot_sav <- data %>%
  filter(countrynewwb %in% c_list_agg) %>%
  # filter(countrynewwb == "LMIC") %>%
  filter(group == "all") %>%
  filter(year %in%  c(2021, 2024)) %>%
  mutate(year = as.character(year)) %>%
  select(countrynewwb, year, ts_anysavings, ts_savfor_fi_mm, ts_savsemfor_MErank) %>%
  ungroup() %>%
  mutate(ts_savother = ts_anysavings - ts_savfor_fi_mm - ts_savsemfor_MErank) %>%
  gather(group, value, ts_savfor_fi_mm, ts_savsemfor_MErank, ts_savother) %>%
  mutate(total = ts_anysavings * 100,
         value = value * 100) %>%
  filter(!is.na(value)) %>%
  mutate(countrynewwb = recode(countrynewwb, !!!legend_labels))

plot_sav$countrynewwb <- ifelse(plot_sav$countrynewwb == "LMIC", 
                                "Low- and middle-income economies", 
                                plot_sav$countrynewwb)

# Check max value
max_val <- max(plot_sav$total, na.rm = TRUE) + 7
if (!is.finite(max_val)) max_val <- 100
if (max_val > 100) max_val <- 100

# Check number of unique countries
length_unique_countries <- plot_sav %>%
  summarise(unique_countries = n_distinct(countrynewwb)) %>%
  pull(unique_countries)

# Dynamically set plot width and height
if (length_unique_countries < 8) {
  width_num <- 8
  height_num <- 4
} else {
  width_num <- 8 + floor((length_unique_countries - 1) / 4) * 2
  height_num <- 4 + floor((length_unique_countries - 1) / 4)
}

# Create the plot
p <- ggplot(plot_sav) +
  geom_bar(aes(x = year,
               y = value,
               fill = factor(group, 
                             levels = c("ts_savother",
                                        "ts_savsemfor_MErank",
                                        "ts_savfor_fi_mm"))),
           stat = "identity", 
           position = "stack",
           width = 0.75,
           color = "black",
           size = 0.75) +
  scale_fill_manual(values = c("#5696D0", "#878787", "#E6E6E6"),
                    breaks = c("ts_savfor_fi_mm",
                               "ts_savsemfor_MErank",
                               "ts_savother"),
                    labels = c("Saved formally",
                               "Saved semiformally",
                               "Saved using other methods only")) +
  scale_y_continuous(limits = c(0, max_val),
                     breaks = seq(0, max_val, by = 20)) +
  # scale_x_discrete(labels = wrap_format(15)) +
  facet_grid(. ~ factor(countrynewwb, levels = c("Low- and middle-income economies","East Asia and Pacific","Europe and Central Asia","Latin America and the Caribbean","Middle East and North Africa",  "South Asia", "Sub-Saharan Africa")),
             scales = "free",
             space = "free",
             switch = "both",
             labeller = label_wrap_gen(width = 15, multi_line = TRUE)) +
  theme(
    strip.placement = "outside",
    strip.text.y.left = element_text(angle = 0),
    strip.text.x = element_text(size = 16, family = "Nunito Sans", colour = "black", angle = 0),
    panel.background = element_blank(),
    strip.background = element_blank(),
    panel.grid.major.x = element_blank(),
    panel.grid.minor.x = element_blank(),
    panel.grid.major.y = element_blank(),
    panel.grid.minor.y = element_blank(),
    panel.border = element_blank(),
    legend.title = element_blank(),
    legend.position = "right",
    legend.justification = "center",
    legend.box.margin = margin(0, 0, 20, 0),
    axis.title.x = element_blank(),
    axis.title.y = element_blank(),
    axis.text.y = element_text(size = 12, color = "black", family = "Nunito Sans"),
    axis.text.x = element_text(size = 12, color = "black", family = "Nunito Sans"),
    axis.ticks.x = element_blank(),
    # axis.ticks.y = element_blank(),
    plot.subtitle = element_text(size = 14,
                                 color = "black",
                                 family = "Nunito Sans"),
    plot.title = element_text(
      hjust = 0,
      size = 16,
      color = "black",
      family = "Nunito Sans",
      face = "bold"
    ),
    plot.title.position = "plot",
    legend.text = element_text(
      hjust = 0,
      size = 16,
      color = "black",
      family = "Nunito Sans"
    ),
    legend.text.align = 0,
    plot.caption.position = "plot",
    plot.caption = element_text(
      hjust = 0,  # Align caption to the left
      size = 10,  # Set caption text size to 10
      color = "black",
      family = "Nunito Sans"
    )
  ) +
  guides(fill = guide_legend(nrow = 3)) +
  labs(
    subtitle = "Adults saving any money in the past year (%), 2024",
    title = "More than two-thirds of adults in low- and middle-income economies\nwho saved did so formally",
    caption = "\nSource: Global Findex Database 2025\n\nNote: People may save in multiple ways, but categories in the figure are constructed to be mutually exclusive. 'Saved formally'\nincludes all adults who saved any money formally. 'Saved semiformally' includes all adults who saved any money semiformally\nbut not formally."
  )
# Show the plot
p

# Save the plot

# Save plot
ggsave(
  filename = file.path(folder_path, "3.1.1.png"),
  plot = p,
  width = 18,
  height = 9,
  units = "in",
  device = 'png',
  dpi = 120
)